package com.rzico.sbl.ui.order

import android.widget.CompoundButton
import android.widget.TextView
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityOrderBatchBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.OrderData
import com.rzico.sbl.other.privacyStatus
import com.rzico.sbl.other.showBatchSendDialog
import com.rzico.sbl.other.userRole
import com.rzico.sbl.viewmodel.OrderViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.getString
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.helper.phoneReplaceWithStar
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.setCompoundDrawable
import com.xinnuo.common_ui.utils.setEmptyImage
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter

class OrderBatchActivity : BaseActivity(R.layout.activity_order_batch) {

    private val mBinding by lazy {
        ActivityOrderBatchBinding.bind(getRootView())
    }

    private var mStatus = ""

    private var mShopArray: Array<String>? = null
    private var mAdminArray: Array<String>? = null
    private var mShopView: TextView? = null
    private var mAdminView: TextView? = null

    override fun getViewModel() = get<OrderViewModel>()

    override fun initData() {
        initTitle(title = "订单列表")

        initLayout()
        initTabLayout()
    }

    private fun initLayout() {
        mBinding
            .batchAll
            .setCompoundDrawable(
                leftSize = 16f,
                leftDrawable = R.drawable.address_default_selector
            )

        mBinding
            .listLayout
            .apply {
                emptyLayout
                    .also {
                        it.emptyImg.setEmptyImage(
                            resId = R.mipmap.icon_order_no,
                            dpSize = 100f
                        )
                        it.emptyHint.text = "暂无相关订单信息！"
                    }

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                    mAdapter = SlimAdapter.creator()
                        .register<OrderData>(R.layout.item_order_batch) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_batch_num, bean.sn)
                                text(
                                    R.id.item_batch_name,
                                    "${bean.consignee}  ${
                                        when {
                                            userRole in "1,2"
                                                    || privacyStatus == "off" -> bean.phone

                                            else -> bean.phone.phoneReplaceWithStar()
                                        }
                                    }"
                                )
                                text(R.id.item_batch_adress, bean.address)
                                text(R.id.item_batch_create, bean.createDate.getTimeString())
                                text(R.id.item_batch_yu, bean.estimateDate.getTimeString())

                                image(
                                    R.id.item_batch_check,
                                    conditionIf(
                                        bean.check,
                                        R.mipmap.login_yes_orange,
                                        R.mipmap.login_no
                                    )
                                )

                                clicked(R.id.item_batch_check) {
                                    bean.check = !bean.check
                                    notifyItemChanged(index)

                                    checkAllSelected()
                                }

                                clicked(R.id.item_batch) {
                                    startActivityEx<OrderDetailActivity>(
                                        "orderSn" to bean.sn,
                                        "shippingSn" to bean.shippingSn
                                    )
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    private fun initTabLayout() {
        mBinding
            .batchTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mStatus = when (it.position) {
                                0 -> "unshipped"
                                else -> ""
                            }

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                addTab(this.newTab().setText("待发货"), true)
            }
    }

    override fun initListener() {
        mBinding.apply {
            batchAll.oneTouch(handle = { mList.isEmpty() })
            batchAll.setOnCheckedChangeListener(this@OrderBatchActivity)

            batchClear.oneClick {
                mList
                    .any { (it as OrderData).check }
                    .condition {
                        mList.forEach { (it as OrderData).check = false }
                        mAdapter.notifyDataSetChanged()

                        checkAllSelected()
                    }
            }

            batchSure.oneClick {
                mList.notEmpty {
                    when {
                        any { (it as OrderData).check } -> {
                            showBatchSendDialog(
                                isForced = true,
                                shopId = getString("shopId"),
                                shopName = getString("shopName"),
                                onShop = { tv, arr ->
                                    mShopView = tv
                                    mShopArray = arr

                                    startActivityEx<OrderShipWhereActivity>()
                                },
                                onAdmin = { tv, arr1, arr2 ->
                                    mAdminView = tv
                                    mShopArray = arr1
                                    mAdminArray = arr2

                                    startActivityEx<OrderShipWhoActivity>(
                                        "shopId" to mShopArray!![0]
                                    )
                                },
                                onSure = { shop, admin, memo ->
                                    val idList =
                                        filter { (it as OrderData).check }
                                            .map { (it as OrderData).id }

                                    getViewModel()
                                        .requestBind(
                                            requestUrl = BaseUrl.orderShipB,
                                            params = arrayOf(
                                                "ids" to idList.joinToString(","),
                                                "shopId" to shop,
                                                "adminId" to admin,
                                                "memo" to memo
                                            )
                                        )
                                        .bindLifeCycle(getLifecycleOwner())
                                        .subscribeBySuccess(
                                            event = getViewModel(),
                                            onSuccess = {
                                                showToast("操作成功！")

                                                updateList()

                                                // 更新运单列表
                                                LiveEventBus
                                                    .get("orderList")
                                                    .post("refresh")
                                            }
                                        )
                                },
                                onDismiss = {
                                    mShopView = null
                                    mAdminView = null
                                    mShopArray = null
                                    mAdminArray = null
                                }
                            )
                        }

                        else -> showToast("请选择要发货的订单")
                    }
                }
            }
        }

        // 监听列表刷新
        observe<String>("batchList") {
            getViewModel()
                .delay { updateList() }
        }

        // 站点、人员监听
        observe<String>("orderShip") { result ->
            val items = result.split(",")
            when (items[0]) {
                "shop" -> {
                    mShopView?.text = items[2]
                    mShopArray?.set(0, items[1])

                    mAdminView?.text = ""
                    mAdminArray?.set(0, "")
                }

                "admin" -> {
                    mAdminView?.text = items[2]
                    mAdminArray?.set(0, items[1])
                }
            }
        }
    }

    /**
     * 全选点击事件监听
     */
    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        mList.forEach { (it as OrderData).check = isChecked }
        mAdapter.notifyDataSetChanged()

        mBinding.batchSure.text = "批量发货(${totalCount()})"
    }

    /**
     * 检查全选按钮状态
     */
    private fun checkAllSelected() {
        mBinding.apply {
            batchAll.setOnCheckedChangeListener(null)

            batchAll.isChecked = mList.isNotEmpty()
                    && mList.none { !(it as OrderData).check }

            batchAll.setOnCheckedChangeListener(this@OrderBatchActivity)

            batchSure.text = "批量发货(${totalCount()})"
        }
    }

    /**
     * 选中数量
     */
    private fun totalCount() = mList.count { (it as OrderData).check }

    /**
     * 批量订单列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .batchList(
                page = index,
                state = mStatus,
                onSuccess = {
                    mList.apply {
                        (index == 0).condition {
                            clear()
                            pageNum = 0
                        }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    checkAllSelected()

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh
                                .isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 列表数据刷新
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh
                    .isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}